import React, { useState, useEffect, useMemo } from 'react';
import { useModel } from 'umi';
import {
  Card,
  Table,
  Button,
  Input,
  Select,
  DatePicker,
  Cascader,
  Modal,
  Form,
  Badge,
  Dropdown,
  Spin,
  Space,
  Typography,
  message,
  Tabs,
  Drawer,
} from 'antd';
import {
  SearchOutlined,
  DownOutlined,
  CalendarOutlined
} from '@ant-design/icons';
import moment from 'moment';
import type { TableProps } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { userindexApi, useraddApi, userdelApi, usereditApi } from '../../api/staff';
import { gradeindexApi, certclassApi, organizationApi } from '../../api/url/index';
import styles from './index.module.css';

const { Title } = Typography;
const { Option } = Select;
const { MonthPicker } = DatePicker;

// ==================== 类型定义 ====================
interface EmployeeItem {
  id: number;
  name: string;
  base_pay: string;
  grade_title: string;
  sex: string;
  birthday: string;
  tel: string;
  idcard: string;
  title: string;
  account: string;
  political_status: string;
  address: string;
  record: string;
  create_time: string;
  status: number;
  layout: number;
  entry_time: string;
  agreement_end: string;
  agreement_num: string;
  bank_card: string;
  bank: string;
  leave_time: string;
  companyid: string;
  projectid: string;
  gradeid: number;
  password?: string;
  dw_security?: string;
  gr_security?: string;
}

interface CompanyOption {
  id: string;
  account: string;
  project: Array<{ id: string; title: string; }>;
}

interface CertOption {
  label: string;
  value: string;
}

interface GradeItem {
  id: number;
  title: string;
  pid: number;
  money: string;
  children?: GradeItem[];
}

interface FormData {
  name: string;
  tel: string;
  idcard: string;
  sex: string;
  birthday: moment.Moment | null;
  address: string;
  gradeid: number[];
  base_pay: string;
  record: string;
  bank: string;
  bank_card: string;
  political_status: string;
  companyid: string;
  projectid: string;
  layout: number;
  status: number;
  agreement_end: moment.Moment | null;
  agreement_num: string;
  entry_time: moment.Moment | null;
  leave_time: moment.Moment | null;
  dw_security?: string;
  gr_security?: string;
}

interface TypeCountMap {
  entry: number;
  leave: number;
  long_dispatch: number;
  short_dispatch: number;
  trainee: number;
  duplicate: number;
}

interface PaginationState {
  current: number;
  pageSize: number;
  total: number;
}

// ==================== 工具函数 ====================
const formatStatus = (status: number) => status === 1 ? '在岗' : '离职';

const formatLayout = (layout: number) => {
  const layoutMap: Record<number, string> = { 1: '长期派遣', 2: '短期派遣', 3: '学员' };
  return layoutMap[layout] || '未知';
};

// 计算员工类型统计数据
const calculateTypeCounts = (data: EmployeeItem[]): TypeCountMap => {
  const nameMap = new Map<string, number>();
  data.forEach(item => {
    if (item.name) nameMap.set(item.name, (nameMap.get(item.name) || 0) + 1);
  });

  return {
    entry: data.filter(item => item.status === 1).length,
    leave: data.filter(item => item.status !== 1).length,
    long_dispatch: data.filter(item => item.layout === 1).length,
    short_dispatch: data.filter(item => item.layout === 2).length,
    trainee: data.filter(item => item.layout === 3).length,
    duplicate: data.filter(item => item.name && (nameMap.get(item.name) || 0) > 1).length,
  };
};

// ==================== 表单验证规则 ====================
// 新增表单验证规则（社保字段不显示，不需要验证）
const addFormRules = {
  name: [{ required: true, message: '请输入姓名' }],
  tel: [
    { required: true, message: '请输入手机号' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入11位有效手机号' }
  ],
  idcard: [
    { required: true, message: '请输入身份证号' },
    { pattern: /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2]\d|3[0-1])\d{3}[\dXx]$/, message: '请输入有效身份证号格式' }
  ],
  address: [{ required: true, message: '请输入籍贯' }],
  gradeid: [{ required: true, message: '请选择岗位档级' }],
  record: [{ required: true, message: '请选择学历' }],
  bank: [{ required: true, message: '请输入开户行' }],
  bank_card: [
    { required: true, message: '请输入银行卡号' },
    { pattern: /^\d{16,19}$/, message: '银行卡号应为16-19位数字' }
  ],
  political_status: [{ required: true, message: '请选择政治面貌' }],
  companyid: [{ required: true, message: '请选择公司' }],
  projectid: [{ required: true, message: '请选择项目' }],
  layout: [{ required: true, message: '请选择用工形式' }],
  status: [{ required: true, message: '请选择员工状态' }],
  agreement_end: [{ required: true, message: '请选择合同到期时间' }],
  agreement_num: [
    { required: true, message: '请输入合同期限' },
    { pattern: /^\d+$/, message: '合同期限应为数字' }
  ],
  entry_time: [{ required: true, message: '请选择入职时间' }],
  leave_time: [{ required: true, message: '请选择离职时间' }],
};

// 编辑表单验证规则（社保字段必填）
const editFormRules = {
  ...addFormRules,
  dw_security: [
    { required: true, message: '请输入单位社保基数' },
    { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入有效的社保基数' }
  ],
  gr_security: [
    { required: true, message: '请输入个人社保基数' },
    { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入有效的社保基数' }
  ]
};

// ==================== 主组件 ====================
const EmployeeManagement: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const [messageApi, contextHolder] = message.useMessage();
  const [form] = Form.useForm();
  const [editForm] = Form.useForm();

  // ==================== 状态管理 ====================
  const [loading, setLoading] = useState<boolean>(false);
  const [visible, setVisible] = useState<boolean>(false);
  const [editModalVisible, setEditModalVisible] = useState<boolean>(false);
  const [editingEmployee, setEditingEmployee] = useState<EmployeeItem | null>(null);
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
  const [selectedCompanyId, setSelectedCompanyId] = useState<string>('');
  const [editSelectedCompanyId, setEditSelectedCompanyId] = useState<string>('');

  // 抽屉状态
  const [drawerVisible, setDrawerVisible] = useState<boolean>(false);
  const [currentEmployee, setCurrentEmployee] = useState<EmployeeItem | null>(null);

  // 搜索筛选状态
  const [nameKey, setNameKey] = useState<string>('');
  const [companyValue, setCompanyValue] = useState<string>('');
  const [projectKey, setProjectKey] = useState<string>('');
  const [gradeName, setGradeName] = useState<string>('');
  const [gradeIdForFilter, setGradeIdForFilter] = useState<number | undefined>();
  const [dateValue, setDateValue] = useState<string>('');
  const [certValue, setCertValue] = useState<string>('');

  // 数据状态
  const [rawTableData, setRawTableData] = useState<EmployeeItem[]>([]);
  const [filteredData, setFilteredData] = useState<EmployeeItem[]>([]);
  const [companyOptions, setCompanyOptions] = useState<CompanyOption[]>([]);
  const [certOptions, setCertOptions] = useState<CertOption[]>([]);
  const [gradeRawData, setGradeRawData] = useState<GradeItem[]>([]);
  const [typeCountMap, setTypeCountMap] = useState<TypeCountMap>({
    entry: 0, leave: 0, long_dispatch: 0, short_dispatch: 0, trainee: 0, duplicate: 0,
  });

  // 分页状态
  const [pagination, setPagination] = useState<PaginationState>({
    current: 1, pageSize: 10, total: 0,
  });

  // ==================== 计算属性 ====================
  const gradeCascaderOptions = useMemo(() => {
    const convertToCascader = (list: GradeItem[], parentId: number = 0): any[] => {
      return list
        .filter(item => item.pid === parentId)
        .map(item => ({
          value: item.id,
          label: `${item.title}`,
          children: convertToCascader(list, item.id),
          money: item.money
        }));
    };
    return convertToCascader(gradeRawData);
  }, [gradeRawData]);

  const currentCompanyProjects = useMemo(() => {
    if (!selectedCompanyId) return [];
    const company = companyOptions.find(company => company.id === selectedCompanyId);
    return company?.project || [];
  }, [selectedCompanyId, companyOptions]);

  const editCompanyProjects = useMemo(() => {
    if (!editSelectedCompanyId) return [];
    const company = companyOptions.find(company => company.id === editSelectedCompanyId);
    return company?.project || [];
  }, [editSelectedCompanyId, companyOptions]);

  const currentPageData = useMemo(() => {
    const start = (pagination.current - 1) * pagination.pageSize;
    const end = start + pagination.pageSize;
    return filteredData.slice(start, end);
  }, [filteredData, pagination.current, pagination.pageSize]);

  // ==================== 生命周期 ====================
  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      try {
        const [companyRes, gradeRes, certRes, employeeRes] = await Promise.allSettled([
          organizationApi().signIn({}).catch(err => ({ data: [] })),
          gradeindexApi().signIn({}).catch(err => ({ list: [] })),
          certclassApi().signIn({}).catch(err => ({ data: [] })),
          userindexApi().signIn({}).catch(err => ({ data: [] })),
        ]);

        setCompanyOptions(companyRes.status === 'fulfilled' && companyRes.value.data ? companyRes.value.data : []);
        setGradeRawData(gradeRes.status === 'fulfilled' && gradeRes.value.list ? gradeRes.value.list : []);
        setCertOptions(certRes.status === 'fulfilled' && certRes.value.data ?
          certRes.value.data.map((item: any) => ({ label: item.title, value: item.id })) : []);

        const employeeData = employeeRes.status === 'fulfilled' && employeeRes.value.data ? employeeRes.value.data : [];
        setRawTableData(employeeData);
        setFilteredData(employeeData);
        setTypeCountMap(calculateTypeCounts(employeeData));
        setPagination(prev => ({ ...prev, total: employeeData.length }));

      } catch (err: any) {
        console.error('数据加载失败:', err);
        messageApi.error('数据加载失败：' + (err.msg || err.message || '网络异常'));
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  useEffect(() => {
    applyFilters();
  }, [nameKey, companyValue, projectKey, gradeIdForFilter, certValue, dateValue, rawTableData]);

  useEffect(() => {
    if (!visible) {
      setSelectedCompanyId('');
    }
  }, [visible]);

  // ==================== 数据操作方法 ====================
  const applyFilters = () => {
    let result = [...rawTableData];

    if (nameKey) {
      const searchName = nameKey.toLowerCase();
      result = result.filter(item => item.name?.toLowerCase().includes(searchName));
    }

    if (companyValue) {
      result = result.filter(item => item.companyid === companyValue);
    }

    if (projectKey) {
      const searchProject = projectKey.toLowerCase();
      result = result.filter(item => item.title?.toLowerCase().includes(searchProject));
    }

    if (gradeIdForFilter !== undefined) {
      result = result.filter(item => item.gradeid === gradeIdForFilter);
    }

    if (certValue) {
      result = result.filter(item => item.idcard?.includes(certValue));
    }

    if (dateValue) {
      try {
        const selectedDate = moment(dateValue);
        const year = selectedDate.year();
        const month = selectedDate.month() + 1;
        result = result.filter(item => {
          if (!item.create_time) return false;
          const itemDate = moment(item.create_time);
          return itemDate.year() === year && itemDate.month() + 1 === month;
        });
      } catch (error) {
        console.warn('日期筛选出错:', error);
      }
    }

    setFilteredData(result);
    setPagination(prev => ({
      ...prev,
      total: result.length,
      current: 1
    }));
  };

  const filterByType = (type: string) => {
    let result = [...rawTableData];
    switch (type) {
      case 'entry': result = result.filter(item => item.status === 1); break;
      case 'leave': result = result.filter(item => item.status !== 1); break;
      case 'long_dispatch': result = result.filter(item => item.layout === 1); break;
      case 'short_dispatch': result = result.filter(item => item.layout === 2); break;
      case 'trainee': result = result.filter(item => item.layout === 3); break;
      case 'duplicate':
        const nameMap = new Map<string, number>();
        result.forEach(item => {
          if (item.name) nameMap.set(item.name, (nameMap.get(item.name) || 0) + 1);
        });
        result = result.filter(item => item.name && (nameMap.get(item.name) || 0) > 1);
        break;
    }
    setFilteredData(result);
    setPagination(prev => ({ ...prev, total: result.length, current: 1 }));
  };

  const resetFilters = () => {
    setNameKey('');
    setCompanyValue('');
    setProjectKey('');
    setGradeName('');
    setGradeIdForFilter(undefined);
    setCertValue('');
    setDateValue('');
    setFilteredData([...rawTableData]);
    setPagination(prev => ({ ...prev, total: rawTableData.length, current: 1 }));
    setSelectedRowKeys([]);
  };

  // ==================== 编辑相关方法 ====================
  const handleDrawerEdit = () => {
    if (currentEmployee) {
      setEditingEmployee(currentEmployee);
      setEditModalVisible(true);
      setEditFormData(currentEmployee);
    }
  };

  const setEditFormData = (employee: EmployeeItem) => {
    const formValues = {
      id: employee.id,
      name: employee.name,
      tel: employee.tel,
      idcard: employee.idcard,
      sex: employee.sex,
      address: employee.address,
      record: employee.record,
      bank_card: employee.bank_card,
      bank: employee.bank,
      political_status: employee.political_status,
      layout: employee.layout,
      status: employee.status,
      companyid: employee.companyid,
      projectid: employee.projectid,
      base_pay: employee.base_pay,
      birthday: employee.birthday ? moment(employee.birthday) : null,
      agreement_end: employee.agreement_end ? moment(employee.agreement_end) : null,
      entry_time: employee.entry_time ? moment(employee.entry_time) : null,
      leave_time: employee.leave_time ? moment(employee.leave_time) : null,
      agreement_num: employee.agreement_num,
      dw_security: employee.dw_security || '',
      gr_security: employee.gr_security || ''
    };

    if (employee.gradeid) {
      formValues.gradeid = [employee.gradeid];
    }

    setEditSelectedCompanyId(employee.companyid);
    editForm.setFieldsValue(formValues);
  };

  const handleEditSubmit = async (values: any) => {
    try {
      setLoading(true);

      // 根据图片中的接口参数准备数据
      const submitData = {
        id: editingEmployee?.id,
        idcard: values.idcard,
        birthday: values.birthday ? values.birthday.format('YYYY-MM-DD') : '',
        sex: values.sex,
        address: values.address,
        record: values.record,
        bank_card: values.bank_card,
        bank: values.bank,
        agreement_end: values.agreement_end ? values.agreement_end.format('YYYY-MM-DD') : '',
        agreement_num: values.agreement_num,
        political_status: values.political_status,
        layout: values.layout,
        status: values.status,
        dw_security: values.dw_security || '',
        gr_security: values.gr_security || '',
        // 补充其他必要字段
        name: values.name,
        tel: values.tel,
        companyid: values.companyid,
        projectid: values.projectid,
        gradeid: values.gradeid && values.gradeid.length > 0 ? values.gradeid[values.gradeid.length - 1] : undefined,
        entry_time: values.entry_time ? values.entry_time.format('YYYY-MM-DD') : '',
        leave_time: values.leave_time ? values.leave_time.format('YYYY-MM-DD') : '',
        base_pay: values.base_pay ? Number(values.base_pay) : undefined
      };

      await usereditApi().signIn(submitData);
      messageApi.success('员工信息更新成功');

      setEditModalVisible(false);
      setEditingEmployee(null);

      const res = await userindexApi().signIn({});
      const employeeData = res.data || [];
      setRawTableData(employeeData);
      setFilteredData(employeeData);
      setTypeCountMap(calculateTypeCounts(employeeData));

    } catch (err: any) {
      console.error('更新员工信息失败:', err);
      messageApi.error('更新失败：' + (err.msg || err.message || '网络异常'));
    } finally {
      setLoading(false);
    }
  };

  const handleEditCancel = () => {
    setEditModalVisible(false);
    setEditingEmployee(null);
    editForm.resetFields();
  };

  // ==================== 事件处理 ====================
  const handleTableChange: TableProps<EmployeeItem>['onChange'] = (pagination) => {
    setPagination({
      current: pagination.current || 1,
      pageSize: pagination.pageSize || 10,
      total: pagination.total || 0,
    });
  };

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys as number[]);
  };

  const handleIdCardBlur = (e: React.FocusEvent<HTMLInputElement>, formInstance: any) => {
    const idcard = formInstance.getFieldValue('idcard');
    if (idcard && idcard.length === 18) {
      const genderNum = parseInt(idcard.charAt(16));
      formInstance.setFieldValue('sex', genderNum % 2 === 0 ? '女' : '男');

      const year = idcard.substring(6, 10);
      const month = idcard.substring(10, 12);
      const day = idcard.substring(12, 14);

      try {
        const birthday = moment(`${year}-${month}-${day}`);
        if (birthday.isValid()) {
          formInstance.setFieldValue('birthday', birthday);
        }
      } catch (error) {
        console.warn('生日解析错误:', error);
      }
    }
  };

  const handleAddIdCardBlur = (e: React.FocusEvent<HTMLInputElement>) => {
    handleIdCardBlur(e, form);
  };

  const handleEditIdCardBlur = (e: React.FocusEvent<HTMLInputElement>) => {
    handleIdCardBlur(e, editForm);
  };

  const handleGradeChange = (value: number[], formInstance: any) => {
    if (!value || value.length === 0) {
      formInstance.setFieldValue('base_pay', '');
      return;
    }

    const currentGradeId = value[value.length - 1];
    const selectedGrade = gradeRawData.find(grade => grade.id === currentGradeId);

    if (selectedGrade) {
      formInstance.setFieldValue('base_pay', selectedGrade.money || '0.00');
    } else {
      formInstance.setFieldValue('base_pay', '');
    }
  };

  const handleAddGradeChange = (value: number[]) => {
    handleGradeChange(value, form);
  };

  const handleEditGradeChange = (value: number[]) => {
    handleGradeChange(value, editForm);
  };

  const handleSearchGradeChange = (value: number[], selectedOptions: any[]) => {
    if (!value || value.length === 0 || !selectedOptions) {
      setGradeName('');
      setGradeIdForFilter(undefined);
      return;
    }
    const currentGradeId = value[value.length - 1];
    const currentGradeName = selectedOptions[selectedOptions.length - 1].label;

    setGradeIdForFilter(currentGradeId);
    setGradeName(currentGradeName);
  };

  const handleCompanyChange = (value: string, formInstance: any, setCompanyId: React.Dispatch<React.SetStateAction<string>>) => {
    formInstance.setFieldValue('projectid', '');
    formInstance.setFieldValue('companyid', value);
    setCompanyId(value);
  };

  const handleAddCompanyChange = (value: string) => {
    handleCompanyChange(value, form, setSelectedCompanyId);
  };

  const handleEditCompanyChange = (value: string) => {
    handleCompanyChange(value, editForm, setEditSelectedCompanyId);
  };

  const handleProjectChange = (value: string, formInstance: any) => {
    formInstance.setFieldValue('projectid', value);
  };

  const handleAddProjectChange = (value: string) => {
    handleProjectChange(value, form);
  };

  const handleEditProjectChange = (value: string) => {
    handleProjectChange(value, editForm);
  };

  const handleStatusChange = (value: number, formInstance: any) => {
    if (value === 1) {
      formInstance.setFieldValue('leave_time', null);
    } else if (value === 2) {
      formInstance.setFieldValue('leave_time', moment());
    }
  };

  const handleAddStatusChange = (value: number) => {
    handleStatusChange(value, form);
  };

  const handleEditStatusChange = (value: number) => {
    handleStatusChange(value, editForm);
  };

  const handleSearchCompanyChange = (value: string) => {
    setCompanyValue(value || '');
  };

  const handleSearchProjectChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setProjectKey(e.target.value);
  };

  const handleSearchCertChange = (value: string) => {
    setCertValue(value || '');
  };

  const handleSearchDateChange = (date: moment.Moment | null) => {
    setDateValue(date ? date.format('YYYY-MM') : '');
  };

  const viewEmployee = (record: EmployeeItem) => {
    setCurrentEmployee(record);
    setDrawerVisible(true);
  };

  const closeDrawer = () => {
    setDrawerVisible(false);
    setCurrentEmployee(null);
  };

  const batchDelete = async () => {
    if (selectedRowKeys.length === 0) {
      messageApi.warning('请先选择要删除的员工');
      return;
    }

    Modal.confirm({
      title: '提示',
      content: `确定要删除选中的 ${selectedRowKeys.length} 名员工吗？`,
      okText: '确定',
      cancelText: '取消',
      centered: true,
      onOk: async () => {
        try {
          await userdelApi().signIn({ id: selectedRowKeys });
          messageApi.success('删除成功');
          const res = await userindexApi().signIn({});
          const employeeData = res.data || [];
          setRawTableData(employeeData);
          setFilteredData(employeeData);
          setTypeCountMap(calculateTypeCounts(employeeData));
          setSelectedRowKeys([]);
        } catch (err: any) {
          console.error('删除失败:', err);
          messageApi.error('删除失败：' + (err.msg || err.message || '网络异常'));
        }
      },
    });
  };

  const showModal = () => {
    setVisible(true);
    form.resetFields();
  };

  const handleCancel = () => {
    setVisible(false);
    form.resetFields();
  };

  const handleSubmit = async (values: any) => {
    try {
      setLoading(true);

      const submitValues = {
        ...values,
        gradeid: values.gradeid && values.gradeid.length > 0 ? values.gradeid[values.gradeid.length - 1] : undefined,
        birthday: values.birthday ? values.birthday.format('YYYY-MM-DD') : '',
        entry_time: values.entry_time ? values.entry_time.format('YYYY-MM-DD') : '',
        agreement_end: values.agreement_end ? values.agreement_end.format('YYYY-MM-DD') : '',
        leave_time: values.leave_time ? values.leave_time.format('YYYY-MM-DD') : '',
        agreement_num: values.agreement_num ? Number(values.agreement_num) : undefined,
        base_pay: values.base_pay ? Number(values.base_pay) : undefined,
        // 新增时不提交社保字段
      };

      await useraddApi().signIn(submitValues);
      messageApi.success('员工添加成功');
      setVisible(false);

      const res = await userindexApi().signIn({});
      const employeeData = res.data || [];
      setRawTableData(employeeData);
      setFilteredData(employeeData);
      setTypeCountMap(calculateTypeCounts(employeeData));

    } catch (err: any) {
      console.error('添加员工失败:', err);
      messageApi.error('添加员工失败：' + (err.msg || err.message || '网络异常'));
    } finally {
      setLoading(false);
    }
  };

  // ==================== 表格列配置 ====================
  const columns: ColumnsType<EmployeeItem> = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      width: 100,
      fixed: 'left',
      align: 'center',
      render: (text, record) => (
        <a
          onClick={() => viewEmployee(record)}
          style={{ color: '#2151C5', cursor: 'pointer', textAlign: 'center' }}
        >
          {text || '-'}
        </a>
      ),
    },
    {
      title: '岗位工资',
      dataIndex: 'base_pay',
      key: 'base_pay',
      width: 100,
      fixed: 'left',
      align: 'center',
      render: (text) => text || '-',
    },
    {
      title: '岗位档级',
      dataIndex: 'grade_title',
      key: 'grade_title',
      width: 100,
      fixed: 'left',
      align: 'center',
      render: (text) => text || '-',
    },
    {
      title: '性别',
      dataIndex: 'sex',
      key: 'sex',
      width: 80,
      align: 'center',
      render: (text) => text || '-',
    },
    {
      title: '生日',
      dataIndex: 'birthday',
      key: 'birthday',
      width: 150,
      align: 'center',
      render: (text) => text ? moment(text).format('YYYY-MM-DD') : '-',
    },
    {
      title: '手机号',
      dataIndex: 'tel',
      key: 'tel',
      width: 150,
      align: 'center',
      render: (text) => text || '-',
    },
    {
      title: '身份证号',
      dataIndex: 'idcard',
      key: 'idcard',
      width: 180,
      align: 'center',
      render: (text) => text || '-',
    },
    {
      title: '项目名称',
      dataIndex: 'title',
      key: 'title',
      width: 150,
      align: 'center',
      render: (text) => text || '-',
    },
    {
      title: '公司名称',
      dataIndex: 'account',
      key: 'account',
      width: 150,
      align: 'center',
      render: (text) => text || '-',
    },
    {
      title: '政治面貌',
      dataIndex: 'political_status',
      key: 'political_status',
      width: 80,
      align: 'center',
      render: (text) => text || '-',
    },
    {
      title: '籍贯',
      dataIndex: 'address',
      key: 'address',
      width: 150,
      align: 'center',
      render: (text) => text || '-',
    },
    {
      title: '学历',
      dataIndex: 'record',
      key: 'record',
      width: 120,
      align: 'center',
      render: (text) => text || '-',
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time',
      width: 150,
      align: 'center',
      render: (text) => text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : '-',
    },
    {
      title: '员工状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      align: 'center',
      render: (status) => formatStatus(status),
    },
    {
      title: '用工形式',
      dataIndex: 'layout',
      key: 'layout',
      width: 100,
      align: 'center',
      render: (layout) => formatLayout(layout),
    },
    {
      title: '入职时间',
      dataIndex: 'entry_time',
      key: 'entry_time',
      width: 150,
      align: 'center',
      render: (text) => text ? moment(text).format('YYYY-MM-DD') : '-',
    },
    {
      title: '合同到期时间',
      dataIndex: 'agreement_end',
      key: 'agreement_end',
      width: 150,
      align: 'center',
      render: (text) => text ? moment(text).format('YYYY-MM-DD') : '-',
    },
    {
      title: '现合同期限',
      dataIndex: 'agreement_num',
      key: 'agreement_num',
      width: 140,
      align: 'center',
      render: (text) => text || '-',
    },
    {
      title: '银行卡号',
      dataIndex: 'bank_card',
      key: 'bank_card',
      width: 200,
      align: 'center',
      render: (text) => text || '-',
    },
    {
      title: '工资卡开户行',
      dataIndex: 'bank',
      key: 'bank',
      width: 200,
      align: 'center',
      render: (text) => text || '-',
    },
    {
      title: '离职时间',
      dataIndex: 'leave_time',
      key: 'leave_time',
      width: 150,
      align: 'center',
      render: (text) => text ? moment(text).format('YYYY-MM-DD') : '-',
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      fixed: 'right',
      align: 'center',
      render: (_, record) => (
        <Dropdown
          menu={{
            items: [
              { key: 'adjustGrade', label: '档级调整' },
              { key: 'adjustPosition', label: '岗位调整' }
            ]
          }}
        >
          <a style={{ color: '#409EFF', cursor: 'pointer', textAlign: 'center' }}>
            更多 <DownOutlined />
          </a>
        </Dropdown>
      ),
    },
  ];

  // ==================== 渲染部分 ====================
  return (
    <>
      {contextHolder}
      <Card style={{ borderRadius: 8, marginBottom: 20, border: 'none', boxShadow: 'none' }}>
        <Title level={4} style={{ margin: 0, marginBottom: 20 }}>员工管理</Title>

        {/* 筛选区 */}
        <div className={styles.filterBar}>
          <div className={styles.filterLeftGroup}>
            <Badge count={typeCountMap.entry} overflowCount={999}>
              <Button onClick={() => filterByType('entry')} className={styles.deleteButton}>入职</Button>
            </Badge>
            <Badge count={typeCountMap.leave} overflowCount={999} color="red">
              <Button type="primary" danger onClick={() => filterByType('leave')} className={styles.deleteButton}>离职</Button>
            </Badge>
            <Badge count={typeCountMap.long_dispatch} overflowCount={999}>
              <Button onClick={() => filterByType('long_dispatch')} className={styles.deleteButton}>长期派遣</Button>
            </Badge>
            <Badge count={typeCountMap.short_dispatch} overflowCount={999}>
              <Button onClick={() => filterByType('short_dispatch')} className={styles.deleteButton}>短期派遣</Button>
            </Badge>
            <Badge count={typeCountMap.trainee} overflowCount={999}>
              <Button onClick={() => filterByType('trainee')} className={styles.deleteButton}>学员</Button>
            </Badge>
            <Badge count={typeCountMap.duplicate} overflowCount={999}>
              <Button onClick={() => filterByType('duplicate')} className={styles.deleteButton}>重复人员</Button>
            </Badge>
            <Button onClick={resetFilters} className={styles.deleteButton}>重置</Button>
          </div>

          <div className={styles.filterRightGroup}>
            <Button type="primary" danger className={styles.deleteButton} onClick={batchDelete}>批量删除</Button>
            <Button type="primary" className={styles.deleteButton}>导出员工</Button>
            <Button type="primary" className={styles.deleteButton}>导入员工</Button>
          </div>
        </div>

        {/* 搜索区 */}
        <div className={styles.searchBar}>
          <div className={styles.searchLeftContainer}>
            <div className={styles.searchGroup}>
              <div className={styles.searchInputWrapper}>
                <Input
                  placeholder="请输入员工姓名"
                  value={nameKey}
                  onChange={(e) => setNameKey(e.target.value)}
                  className={styles.searchInput}
                />
                <SearchOutlined className={styles.searchIcon} />
              </div>

              <Select
                placeholder="请选择公司"
                value={companyValue || undefined}
                onChange={handleSearchCompanyChange}
                allowClear
                className={styles.searchSelect}
              >
                {companyOptions.map(company => (
                  <Option key={company.id} value={company.id}>{company.account}</Option>
                ))}
              </Select>

              <div className={styles.searchInputWrapper}>
                <Input
                  placeholder="请输入项目名称"
                  value={projectKey}
                  onChange={handleSearchProjectChange}
                  className={styles.searchInput}
                />
                <SearchOutlined className={styles.searchIcon} />
              </div>

              <Cascader
                placeholder="请选择档级"
                value={gradeIdForFilter ? [gradeIdForFilter] : undefined}
                options={gradeCascaderOptions}
                onChange={handleSearchGradeChange}
                allowClear
                className={styles.searchCascader}
                displayRender={() => gradeName || ''}
              />

              <Select
                placeholder="请选择证书"
                value={certValue || undefined}
                onChange={handleSearchCertChange}
                allowClear
                className={styles.searchSelect}
              >
                {certOptions.map(cert => (
                  <Option key={cert.value} value={cert.value}>{cert.label}</Option>
                ))}
              </Select>

              <DatePicker.MonthPicker
                placeholder="请选择年月"
                value={dateValue ? moment(dateValue) : null}
                onChange={handleSearchDateChange}
                allowClear
                className={styles.searchDatePicker}
              />
            </div>
          </div>

          <div className={styles.addButtonContainer}>
            <Button type="primary" className={styles.deleteButton} onClick={showModal}>新增</Button>
          </div>
        </div>

        {/* 员工列表表格 */}
        <Spin spinning={loading}>
          <Table
            rowKey="id"
            dataSource={currentPageData}
            columns={columns}
            className={styles.customTable}
            pagination={{
              current: pagination.current,
              pageSize: pagination.pageSize,
              total: pagination.total,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条记录`,
            }}
            onChange={handleTableChange}
            rowSelection={{ selectedRowKeys, onChange: onSelectChange }}
            scroll={{ x: 'max-content' }}
            bordered
          />
        </Spin>

        {/* 抽屉组件 */}
        <Drawer
          title={<span>{currentEmployee?.name || '员工信息'}</span>}
          placement="right"
          width={1100}
          closable={{ placement: 'end' }}
          onClose={closeDrawer}
          open={drawerVisible}
          bodyStyle={{ paddingTop: '5px' }}
        >
          <Tabs defaultActiveKey="basic" className={styles.tabs}>
            <Tabs.TabPane tab="基本信息" key="basic">
              <div className={styles.tabContent}>
                <span className={styles.tabTitle}>岗位信息</span>
                <span
                  className={styles.editBtn}
                  onClick={handleDrawerEdit}
                  style={{ cursor: 'pointer', color: '#1890ff' }}
                >
                  编辑
                </span>
              </div>
              <div className={styles.tabInfoContent}>
                <div className={styles.infoGrid}>
                  <div className={styles.infoItem}>
                    <span className={styles.label}>姓名</span>
                    <Input className={styles.input} value={currentEmployee?.name || ''} disabled />
                  </div>
                  <div className={styles.infoItem}>
                    <span className={styles.label}>性别</span>
                    <Input className={styles.input} value={currentEmployee?.sex || ''} disabled />
                  </div>
                  <div className={styles.infoItem}>
                    <span className={styles.label}>籍贯</span>
                    <Input className={styles.input} value={currentEmployee?.address || ''} disabled />
                  </div>
                  <div className={styles.infoItem}>
                    <span className={styles.label}>学历</span>
                    <Input className={styles.input} value={currentEmployee?.record || ''} disabled />
                  </div>
                  <div className={styles.infoItem}>
                    <span className={styles.label}>电话</span>
                    <Input className={styles.input} value={currentEmployee?.tel || ''} disabled />
                  </div>
                  <div className={styles.infoItem}>
                    <span className={styles.label}>政治面貌</span>
                    <Input className={styles.input} value={currentEmployee?.political_status || ''} disabled />
                  </div>
                  <div className={styles.infoItem}>
                    <span className={styles.label}>身份证号</span>
                    <Input className={styles.input} value={currentEmployee?.idcard || ''} disabled />
                  </div>
                  <div className={styles.infoItem}>
                    <span className={styles.label}>银行卡号</span>
                    <Input className={styles.input} value={currentEmployee?.bank_card || ''} disabled />
                  </div>
                  <div className={styles.infoItem}>
                    <span className={styles.label}>所在公司</span>
                    <Input className={styles.input} value={currentEmployee?.account || ''} disabled />
                  </div>
                  <div className={styles.infoItem}>
                    <span className={styles.label}>用工形式</span>
                    <Input
                      className={styles.input}
                      value={
                        currentEmployee?.layout === 1 ? '长期派遣' :
                          currentEmployee?.layout === 2 ? '短期派遣' :
                            currentEmployee?.layout === 3 ? '学员' : '-'
                      }
                      disabled
                    />
                  </div>
                  <div className={styles.infoItem}>
                    <span className={styles.label}>档级</span>
                    <Input className={styles.input} value={currentEmployee?.grade_title || ''} disabled />
                  </div>
                  <div className={styles.infoItem}>
                    <span className={styles.label}>基本工资</span>
                    <Input className={styles.input} value={currentEmployee?.base_pay || ''} disabled />
                  </div>
                  <div className={styles.infoItem}>
                    <span className={styles.label}>创建时间</span>
                    <Input className={styles.input} value={currentEmployee?.create_time || ''} disabled />
                  </div>
                  <div className={styles.infoItem}>
                    <span className={styles.label}>所属项目</span>
                    <Input className={styles.input} value={currentEmployee?.title || ''} disabled />
                  </div>
                  <div className={styles.infoItem}>
                    <span className={styles.label}>开户行</span>
                    <Input className={styles.input} value={currentEmployee?.bank || ''} disabled />
                  </div>
                  <div className={styles.infoItem}>
                    <span className={styles.label}>到期时间</span>
                    <Input className={styles.input} value={currentEmployee?.agreement_end || ''} disabled />
                  </div>
                  <div className={styles.infoItem}>
                    <span className={styles.label}>签订年数</span>
                    <Input className={styles.input} value={currentEmployee?.agreement_num || ''} disabled />
                  </div>
                  <div className={styles.infoItem}>
                    <span className={styles.label}>密码</span>
                    <Input className={styles.input} value={currentEmployee?.password || ''} disabled />
                  </div>
                  <div className={styles.infoItem}>
                    <span className={styles.label}>单位社保基数</span>
                    <Input className={styles.input} value={currentEmployee?.dw_security || '-'} disabled />
                  </div>
                  <div className={styles.infoItem}>
                    <span className={styles.label}>个人社保基数</span>
                    <Input className={styles.input} value={currentEmployee?.gr_security || '-'} disabled />
                  </div>
                  <div className={styles.infoItem}>
                    <span className={styles.label}>入职时间</span>
                    <Input className={styles.input} value={currentEmployee?.entry_time || ''} disabled />
                  </div>
                  <div className={styles.infoItem}>
                    <span className={styles.label}>离职时间</span>
                    <Input className={styles.input} value={currentEmployee?.leave_time || ''} disabled />
                  </div>
                </div>
              </div>
            </Tabs.TabPane>
            <Tabs.TabPane tab="员工合同" key="work">
              <div style={{ backgroundColor: '#fff', borderRadius: '8px' }}>
                {/* 操作说明标题 */}
                <h2 style={{ marginBottom: '10px', color: '#333', fontSize: '18px', fontWeight: 'bold' }}>操作说明：</h2>
                {/* 操作步骤列表 */}
                <div style={{ marginBottom: '5px' }}>
                  <h3 style={{ color: '#333', fontSize: '14px', margin: '3px 0', fontWeight: 'normal' }}>
                    1、点击新增创建合同
                  </h3>
                  <h3 style={{ color: '#333', fontSize: '14px', margin: '3px 0', fontWeight: 'normal' }}>
                    2、点击签署，发起合同签章，甲乙双方根据收到的短信链接点击后进行签署
                  </h3>
                  <h3 style={{ color: '#333', fontSize: '14px', margin: '3px 0', fontWeight: 'normal' }}>
                    3、甲乙双方签署成功后，点击归档，合同签署流程结束
                  </h3>
                  <h3 style={{ color: '#333', fontSize: '14px', margin: '3px 0', fontWeight: 'normal' }}>
                    4、乙方尚未签署时，甲方可撤回修改重新发起签署
                  </h3>
                </div>

                {/* 新增按钮 */}
                <div style={{ marginBottom: '16px' }}>
                  <Button type="primary">
                    新增
                  </Button>
                </div>

                {/* 合同表格*/}
                <Table
                  dataSource={[]}
                  components={{
                    header: {
                      cell: (props: any) => (
                        <th {...props} style={{ ...props.style, color: '#999999', fontWeight: 'normal' }} />
                      )
                    }
                  }}
                  bordered
                  columns={[
                    {
                      title: '合同名称',
                      dataIndex: 'contractName',
                      key: 'contractName',
                      width: 150,
                      align: 'center',
                      fixed: 'left', // 固定第一列
                      render: (text) => text || '-'
                    },
                    {
                      title: '乙方姓名',
                      dataIndex: 'partyBName',
                      key: 'partyBName',
                      width: 120,
                      align: 'center',
                      render: (text) => text || '-'
                    },
                    {
                      title: '合同类型',
                      dataIndex: 'contractType',
                      key: 'contractType',
                      width: 120,
                      align: 'center',
                      render: (text) => text || '-'
                    },
                    {
                      title: '合同开始时间',
                      dataIndex: 'startTime',
                      key: 'startTime',
                      width: 150,
                      align: 'center',
                      render: (text) => text || '-'
                    },
                    {
                      title: '合同结束时间',
                      dataIndex: 'endTime',
                      key: 'endTime',
                      width: 150,
                      align: 'center',
                      render: (text) => text || '-'
                    },
                    {
                      title: '合同状态',
                      dataIndex: 'contractStatus',
                      key: 'contractStatus',
                      width: 100,
                      align: 'center',
                      render: (text) => text || '-'
                    },
                    {
                      title: '操作',
                      key: 'action',
                      width: 350,
                      align: 'center',
                      fixed: 'right',
                    }
                  ]}
                  pagination={false}
                  scroll={{ x: 1000 }} // 设置横向滚动，确保固定列生效
                  locale={{
                    emptyText: (
                      <div style={{ padding: '40px 0', color: '#999' }}>
                        暂无数据
                      </div>
                    )
                  }}
                />
              </div>
            </Tabs.TabPane>
            <Tabs.TabPane tab="工资社保" key="salary">
              <div>
                {/* 批次时间选择器 */}
                <div style={{ marginBottom: 16 }}>
                  <MonthPicker
                    placeholder="请选择批次时间"
                    style={{ width: 200 }}
                    allowClear
                    format="YYYY-MM"
                  />
                </div>

                {/* 工资表格 - 调整为图片一样式，固定前两列和最后一列 */}
                <Table
                  columns={[
                    // 固定列：前两列
                    {
                      title: '序号',
                      dataIndex: 'index',
                      key: 'index',
                      width: 60,
                      align: 'center',
                      fixed: 'left',
                      render: (text, record, index) => index + 1
                    },
                    {
                      title: '姓名',
                      dataIndex: 'name',
                      key: 'name',
                      width: 100,
                      align: 'center',
                      fixed: 'left',
                    },

                    // 基础信息列
                    {
                      title: '工资所属日期',
                      dataIndex: 'salaryDate',
                      key: 'salaryDate',
                      width: 120,
                      align: 'center',
                    },
                    {
                      title: '用工形式',
                      dataIndex: 'employmentType',
                      key: 'employmentType',
                      width: 100,
                      align: 'center',
                    },
                    {
                      title: '职务',
                      dataIndex: 'position',
                      key: 'position',
                      width: 100,
                      align: 'center',
                    },
                    {
                      title: '薪水等级',
                      dataIndex: 'salaryLevel',
                      key: 'salaryLevel',
                      width: 100,
                      align: 'center',
                    },

                    // 薪资待遇标准子列
                    {
                      title: '薪资待遇标准',
                      key: 'salaryStandard',
                      children: [
                        {
                          title: '岗位工资',
                          dataIndex: 'postWage',
                          key: 'postWage',
                          width: 100,
                          align: 'center',
                        },
                        {
                          title: '安全质量奖金',
                          dataIndex: 'safetyBonus',
                          key: 'safetyBonus',
                          width: 120,
                          align: 'center',
                        },
                        {
                          title: '岗位津贴',
                          dataIndex: 'postAllowance',
                          key: 'postAllowance',
                          width: 100,
                          align: 'center',
                        },
                        {
                          title: '绩效奖金',
                          dataIndex: 'performanceBonus',
                          key: 'performanceBonus',
                          width: 100,
                          align: 'center',
                        },
                      ],
                    },

                    // 出勤信息列
                    {
                      title: '应出勤天数',
                      dataIndex: 'shouldAttendDays',
                      key: 'shouldAttendDays',
                      width: 120,
                      align: 'center',
                    },
                    {
                      title: '实际出勤天数',
                      dataIndex: 'actualAttendDays',
                      key: 'actualAttendDays',
                      width: 120,
                      align: 'center',
                    },

                    // 补贴扣款列
                    {
                      title: '误餐补贴',
                      dataIndex: 'mealAllowance',
                      key: 'mealAllowance',
                      width: 100,
                      align: 'center',
                    },
                    {
                      title: '租房补贴',
                      dataIndex: 'rentAllowance',
                      key: 'rentAllowance',
                      width: 100,
                      align: 'center',
                    },
                    {
                      title: '高温补贴',
                      dataIndex: 'highTempAllowance',
                      key: 'highTempAllowance',
                      width: 100,
                      align: 'center',
                    },
                    {
                      title: '取暖补贴',
                      dataIndex: 'heatingAllowance',
                      key: 'heatingAllowance',
                      width: 100,
                      align: 'center',
                    },
                    {
                      title: '外出施工补贴',
                      dataIndex: 'constructionAllowance',
                      key: 'constructionAllowance',
                      width: 130,
                      align: 'center',
                    },
                    {
                      title: '奖金',
                      dataIndex: 'bonus',
                      key: 'bonus',
                      width: 80,
                      align: 'center',
                    },
                    {
                      title: '其他补助',
                      dataIndex: 'otherAllowance',
                      key: 'otherAllowance',
                      width: 100,
                      align: 'center',
                    },
                    {
                      title: '扣款',
                      dataIndex: 'deduction',
                      key: 'deduction',
                      width: 80,
                      align: 'center',
                    },

                    // 社保个税列
                    {
                      title: '应发小计',
                      dataIndex: 'payableSubtotal',
                      key: 'payableSubtotal',
                      width: 100,
                      align: 'center',
                    },
                    {
                      title: '个人社保',
                      dataIndex: 'personalSocial',
                      key: 'personalSocial',
                      width: 100,
                      align: 'center',
                    },
                    {
                      title: '个税',
                      dataIndex: 'incomeTax',
                      key: 'incomeTax',
                      width: 80,
                      align: 'center',
                    },
                    {
                      title: '实发小计',
                      dataIndex: 'actualSubtotal',
                      key: 'actualSubtotal',
                      width: 100,
                      align: 'center',
                    },
                    {
                      title: '单位社保',
                      dataIndex: 'companySocial',
                      key: 'companySocial',
                      width: 100,
                      align: 'center',
                    },
                    {
                      title: '管理费',
                      dataIndex: 'managementFee',
                      key: 'managementFee',
                      width: 80,
                      align: 'center',
                    },

                    // 辅助信息列
                    {
                      title: '电话',
                      dataIndex: 'phone',
                      key: 'phone',
                      width: 120,
                      align: 'center',
                    },
                    {
                      title: '身份证号',
                      dataIndex: 'idCard',
                      key: 'idCard',
                      width: 180,
                      align: 'center',
                    },
                    {
                      title: '银行卡',
                      dataIndex: 'bankCard',
                      key: 'bankCard',
                      width: 180,
                      align: 'center',
                    },
                    {
                      title: '审计批次',
                      dataIndex: 'auditBatch',
                      key: 'auditBatch',
                      width: 120,
                      align: 'center',
                    },

                    // 固定列：最后一列
                    {
                      title: '合计金额',
                      dataIndex: 'totalAmount',
                      key: 'totalAmount',
                      width: 100,
                      align: 'center',
                      fixed: 'right',
                    },
                  ]}
                  dataSource={[]}
                  locale={{
                    emptyText: (
                      <div style={{
                        padding: '40px 0',
                        color: '#999',
                        textAlign: 'center',
                        fontSize: '14px'
                      }}>
                        暂无数据
                      </div>
                    )
                  }}
                  bordered
                  pagination={false}
                  style={{
                    marginBottom: 16,
                    width: '100%'
                  }}
                  scroll={{
                    x: 3200, // 适配所有列宽总和
                    y: '20'
                  }}
                  components={{
                    header: {
                      cell: (props) => (
                        <th {...props} style={{
                          ...props.style,
                          backgroundColor: '#fafafa',
                          color: '#666',
                          fontWeight: 'normal',
                          textAlign: 'center',
                          borderRight: '1px solid #e8e8e8'
                        }} />
                      )
                    },
                    body: {
                      cell: (props) => (
                        <td {...props} style={{
                          ...props.style,
                          textAlign: 'center',
                          verticalAlign: 'middle',
                          borderRight: '1px solid #e8e8e8'
                        }} />
                      )
                    }
                  }}
                  onRow={() => ({
                    style: {
                      backgroundColor: '#fff',
                    },
                  })}
                />
                {/* 底部分页组件 - 完全匹配布局 */}
                <div style={{ textAlign: 'center', paddingTop: 8 }}>
                  <Select
                    defaultValue="10"
                    style={{ width: 100, marginRight: 16, fontSize: 14 }}
                    options={[
                      { value: '10', label: '10条/页' },
                      { value: '20', label: '20条/页' },
                      { value: '50', label: '50条/页' },
                    ]}
                    bordered
                  />
                  <span style={{ marginRight: 16, fontSize: 14, color: '#666' }}>共 0 条</span>
                </div>
              </div>
            </Tabs.TabPane>
            <Tabs.TabPane tab="证书列表" key="certificate">
              <div className={styles.tabContent}>
                <div>
                  {/* 证书网格布局 - 3列等宽，间距统一 */}
                  <div style={{
                    display: 'grid',
                    gridTemplateColumns: 'repeat(3, 1fr)',
                    gap: '16px',
                    maxWidth: '800px', // 限制最大宽度，避免卡片过宽
                    margin: '0 auto'
                  }}>
                    {/* 毕业证 */}
                    <div style={{
                      height: '160px',
                      width: '300px',
                      border: '1px solid #d9d9d9',
                      borderRadius: '6px',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center', // 文字整体居中
                      boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
                    }}>
                      <span style={{
                        fontSize: '16px',
                        color: '#000',
                        fontWeight: 'normal',
                        display: 'flex',
                        alignItems: 'center',
                        gap: '8px' // 文字与图标间距
                      }}>
                        毕业证
                        <span style={{ fontSize: '14px' }}>↑</span>
                      </span>
                    </div>

                    {/* 电工证1sq */}
                    <div style={{
                      height: '160px',
                      width: '300px',
                      border: '1px solid #d9d9d9',
                      borderRadius: '6px',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center', // 文字整体居中
                      boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
                    }}>
                      <span style={{
                        fontSize: '16px',
                        color: '#000',
                        fontWeight: 'normal',
                        display: 'flex',
                        alignItems: 'center',
                        gap: '8px'
                      }}>
                        电工证1sq
                        <span style={{ fontSize: '14px' }}>↑</span>
                      </span>
                    </div>

                    {/* 驾驶证 */}
                    <div style={{
                      height: '160px',
                      width: '300px',
                      border: '1px solid #d9d9d9',
                      borderRadius: '6px',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center', // 文字整体居中
                      boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
                    }}>
                      <span style={{
                        fontSize: '16px',
                        color: '#000',
                        fontWeight: 'normal',
                        display: 'flex',
                        alignItems: 'center',
                        gap: '8px'
                      }}>
                        驾驶证
                        <span style={{ fontSize: '14px' }}>↑</span>
                      </span>
                    </div>

                    {/* 荣誉证 */}
                    <div style={{
                      height: '160px',
                      width: '300px',
                      border: '1px solid #d9d9d9',
                      borderRadius: '6px',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center', // 文字整体居中
                      boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
                    }}>
                      <span style={{
                        fontSize: '16px',
                        color: '#000',
                        fontWeight: 'normal',
                        display: 'flex',
                        alignItems: 'center',
                        gap: '8px'
                      }}>
                        荣誉证
                        <span style={{ fontSize: '14px' }}>↑</span>
                      </span>
                    </div>

                    {/* 技工证 */}
                    <div style={{
                      height: '160px',
                      width: '300px',
                      border: '1px solid #d9d9d9',
                      borderRadius: '6px',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center', // 文字整体居中
                      boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
                    }}>
                      <span style={{
                        fontSize: '16px',
                        color: '#000',
                        fontWeight: 'normal',
                        display: 'flex',
                        alignItems: 'center',
                        gap: '8px'
                      }}>
                        技工证
                        <span style={{ fontSize: '14px' }}>↑</span>
                      </span>
                    </div>

                    {/* 学位证 */}
                    <div style={{
                      height: '160px',
                      width: '300px',
                      border: '1px solid #d9d9d9',
                      borderRadius: '6px',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center', // 文字整体居中
                      boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
                    }}>
                      <span style={{
                        fontSize: '16px',
                        color: '#000',
                        fontWeight: 'normal',
                        display: 'flex',
                        alignItems: 'center',
                        gap: '8px'
                      }}>
                        学位证
                        <span style={{ fontSize: '14px' }}>↑</span>
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </Tabs.TabPane>
          </Tabs>
        </Drawer>

        {/* 新增员工弹窗 - 隐藏社保字段 */}
        <Modal title="添加人员信息" open={visible} onCancel={handleCancel} footer={null} centered width={800} destroyOnClose>
          <Form
            form={form}
            layout="vertical"
            onFinish={handleSubmit}
            initialValues={{
              sex: '', base_pay: '', gradeid: [], layout: undefined, status: undefined,
              political_status: '', record: '', leave_time: null
            }}
            style={{ margin: 0, padding: 0 }}
          >
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '0 16px' }}>
              {/* 第一行：姓名、手机号、身份证号 */}
              <Form.Item name="name" label="姓名" rules={addFormRules.name} style={{ marginBottom: 12 }}>
                <Input placeholder="请输入姓名" size="middle" style={{ height: 34 }} />
              </Form.Item>
              <Form.Item name="tel" label="手机号" rules={addFormRules.tel} style={{ marginBottom: 12 }}>
                <Input
                  placeholder="请输入手机号"
                  maxLength={11}
                  onChange={(e) => {
                    const value = e.target.value.replace(/[^\d]/g, '');
                    form.setFieldValue('tel', value);
                  }}
                  size="middle"
                  style={{ height: 34 }}
                />
              </Form.Item>
              <Form.Item name="idcard" label="身份证号" rules={addFormRules.idcard} style={{ marginBottom: 12 }}>
                <Input
                  placeholder="请输入身份证号"
                  maxLength={18}
                  onBlur={handleAddIdCardBlur}
                  onChange={(e) => {
                    const value = e.target.value.replace(/[^\dXx]/g, '').toUpperCase();
                    form.setFieldValue('idcard', value);
                  }}
                  size="middle"
                  style={{ height: 34 }}
                />
              </Form.Item>

              {/* 第二行：性别、生日、籍贯 */}
              <Form.Item name="sex" label="性别" style={{ marginBottom: 12 }}>
                <Input placeholder="输入身份证号自动填充" disabled size="middle" style={{ height: 34 }} />
              </Form.Item>
              <Form.Item name="birthday" label="生日" style={{ marginBottom: 12 }}>
                <DatePicker placeholder="输入身份证号自动填充" disabled style={{ width: '100%', height: 34 }} />
              </Form.Item>
              <Form.Item name="address" label="籍贯" rules={addFormRules.address} style={{ marginBottom: 12 }}>
                <Input placeholder="请输入籍贯" size="middle" style={{ height: 34 }} />
              </Form.Item>

              {/* 第三行：岗位档级、岗位工资、学历 */}
              <Form.Item name="gradeid" label="岗位档级" rules={addFormRules.gradeid} style={{ marginBottom: 12 }}>
                <Cascader
                  placeholder="请选择档级"
                  options={gradeCascaderOptions}
                  onChange={handleAddGradeChange}
                  allowClear
                  style={{ width: '100%', height: 34 }}
                />
              </Form.Item>
              <Form.Item name="base_pay" label="岗位工资" style={{ marginBottom: 12 }}>
                <Input placeholder="选择档级后自动填充" disabled size="middle" style={{ height: 34 }} />
              </Form.Item>
              <Form.Item name="record" label="学历" rules={addFormRules.record} style={{ marginBottom: 12 }}>
                <Select placeholder="请选择学历" size="middle" style={{ height: 34 }}>
                  <Option value="">请选择</Option>
                  <Option value="高中">高中</Option>
                  <Option value="大专">大专</Option>
                  <Option value="本科">本科</Option>
                  <Option value="研究生">研究生</Option>
                  <Option value="博士">博士</Option>
                </Select>
              </Form.Item>

              {/* 第四行：开户行、银行卡号、政治面貌 */}
              <Form.Item name="bank" label="开户行" rules={addFormRules.bank} style={{ marginBottom: 12 }}>
                <Input placeholder="请输入开户行" size="middle" style={{ height: 34 }} />
              </Form.Item>
              <Form.Item name="bank_card" label="银行卡号" rules={addFormRules.bank_card} style={{ marginBottom: 12 }}>
                <Input
                  placeholder="请输入银行卡号"
                  onChange={(e) => {
                    const value = e.target.value.replace(/[^\d]/g, '');
                    form.setFieldValue('bank_card', value);
                  }}
                  size="middle"
                  style={{ height: 34 }}
                />
              </Form.Item>
              <Form.Item name="political_status" label="政治面貌" rules={addFormRules.political_status} style={{ marginBottom: 12 }}>
                <Select placeholder="请选择政治面貌" size="middle" style={{ height: 34 }}>
                  <Option value="">请选择</Option>
                  <Option value="群众">群众</Option>
                  <Option value="团员">团员</Option>
                  <Option value="党员">党员</Option>
                  <Option value="其他">其他</Option>
                </Select>
              </Form.Item>

              {/* 第五行：公司、项目、用工形式 */}
              <Form.Item name="companyid" label="公司" rules={addFormRules.companyid} style={{ marginBottom: 12 }}>
                <Select
                  placeholder="请选择公司"
                  onChange={handleAddCompanyChange}
                  size="middle"
                  style={{ height: 34 }}
                >
                  {companyOptions.map(company => <Option key={company.id} value={company.id}>{company.account}</Option>)}
                </Select>
              </Form.Item>
              <Form.Item name="projectid" label="项目" rules={addFormRules.projectid} style={{ marginBottom: 12 }}>
                <Select
                  placeholder={form.getFieldValue('companyid') ? "请选择项目" : "请先选择公司"}
                  onChange={handleAddProjectChange}
                  size="middle"
                  style={{ height: 34 }}
                >
                  {currentCompanyProjects.map(project => (
                    <Option key={project.id} value={project.id}>{project.title}</Option>
                  ))}
                </Select>
              </Form.Item>
              <Form.Item name="layout" label="用工形式" rules={addFormRules.layout} style={{ marginBottom: 12 }}>
                <Select placeholder="请选择用工形式" size="middle" style={{ height: 34 }}>
                  <Option value="">请选择</Option>
                  <Option value={1}>长期派遣</Option>
                  <Option value={2}>短期派遣</Option>
                  <Option value={3}>学员</Option>
                </Select>
              </Form.Item>

              {/* 第六行：员工状态、合同到期时间、现合同期限 */}
              <Form.Item name="status" label="员工状态" rules={addFormRules.status} style={{ marginBottom: 12 }}>
                <Select
                  placeholder="请选择员工状态"
                  onChange={handleAddStatusChange}
                  size="middle"
                  style={{ height: 34 }}
                >
                  <Option value="">请选择</Option>
                  <Option value={1}>在岗</Option>
                  <Option value={2}>离职</Option>
                </Select>
              </Form.Item>
              <Form.Item name="agreement_end" label="合同到期时间" rules={addFormRules.agreement_end} style={{ marginBottom: 12 }}>
                <DatePicker style={{ width: '100%', height: 34 }} />
              </Form.Item>
              <Form.Item name="agreement_num" label="现合同期限" rules={addFormRules.agreement_num} style={{ marginBottom: 12 }}>
                <Input
                  placeholder="请输入合同期限"
                  onChange={(e) => {
                    const value = e.target.value.replace(/[^\d]/g, '');
                    form.setFieldValue('agreement_num', value);
                  }}
                  size="middle"
                  style={{ height: 34 }}
                />
              </Form.Item>

              {/* 第七行：入职时间、离职时间 */}
              <Form.Item name="entry_time" label="入职时间" rules={addFormRules.entry_time} style={{ marginBottom: 12 }}>
                <DatePicker style={{ width: '100%', height: 34 }} />
              </Form.Item>
              <Form.Item name="leave_time" label="离职时间" rules={addFormRules.leave_time} style={{ marginBottom: 0 }}>
                <DatePicker style={{ width: '100%', height: 34 }} />
              </Form.Item>
              <Form.Item /> {/* 占位，保持网格对齐 */}
            </div>

            <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 16, gap: 8 }}>
              <Button onClick={handleCancel} size="middle" style={{ height: 34, padding: '0 16px' }}>取消</Button>
              <Button type="primary" htmlType="submit" loading={loading} size="middle" style={{ height: 34, padding: '0 16px' }}>确认添加</Button>
            </div>
          </Form>
        </Modal>

        {/* 编辑员工弹窗 - 显示社保字段且必填 */}
        <Modal
          title="编辑人员信息"
          open={editModalVisible}
          onCancel={handleEditCancel}
          footer={null}
          centered
          width={800}
          destroyOnClose
        >
          <Form
            form={editForm}
            layout="vertical"
            onFinish={handleEditSubmit}
            initialValues={{
              sex: '', base_pay: '', gradeid: [], layout: undefined, status: undefined,
              political_status: '', record: '', leave_time: null, dw_security: '', gr_security: ''
            }}
            style={{ margin: 0, padding: 0 }}
          >
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '0 16px' }}>
              {/* 第一行：姓名、手机号、身份证号 */}
              <Form.Item name="name" label="姓名" rules={editFormRules.name} style={{ marginBottom: 12 }}>
                <Input placeholder="请输入姓名" size="middle" style={{ height: 34 }} />
              </Form.Item>
              <Form.Item name="tel" label="手机号" rules={editFormRules.tel} style={{ marginBottom: 12 }}>
                <Input
                  placeholder="请输入手机号"
                  maxLength={11}
                  onChange={(e) => {
                    const value = e.target.value.replace(/[^\d]/g, '');
                    editForm.setFieldValue('tel', value);
                  }}
                  size="middle"
                  style={{ height: 34 }}
                />
              </Form.Item>
              <Form.Item name="idcard" label="身份证号" rules={editFormRules.idcard} style={{ marginBottom: 12 }}>
                <Input
                  placeholder="请输入身份证号"
                  maxLength={18}
                  onBlur={handleEditIdCardBlur}
                  onChange={(e) => {
                    const value = e.target.value.replace(/[^\dXx]/g, '').toUpperCase();
                    editForm.setFieldValue('idcard', value);
                  }}
                  size="middle"
                  style={{ height: 34 }}
                />
              </Form.Item>

              {/* 第二行：性别、生日、籍贯 */}
              <Form.Item name="sex" label="性别" style={{ marginBottom: 12 }}>
                <Input placeholder="输入身份证号自动填充" disabled size="middle" style={{ height: 34 }} />
              </Form.Item>
              <Form.Item name="birthday" label="生日" style={{ marginBottom: 12 }}>
                <DatePicker placeholder="输入身份证号自动填充" disabled style={{ width: '100%', height: 34 }} />
              </Form.Item>
              <Form.Item name="address" label="籍贯" rules={editFormRules.address} style={{ marginBottom: 12 }}>
                <Input placeholder="请输入籍贯" size="middle" style={{ height: 34 }} />
              </Form.Item>

              {/* 第三行：岗位档级、岗位工资、学历 */}
              <Form.Item name="gradeid" label="岗位档级" rules={editFormRules.gradeid} style={{ marginBottom: 12 }}>
                <Cascader
                  placeholder="请选择档级"
                  options={gradeCascaderOptions}
                  onChange={handleEditGradeChange}
                  allowClear
                  style={{ width: '100%', height: 34 }}
                />
              </Form.Item>
              <Form.Item name="base_pay" label="岗位工资" style={{ marginBottom: 12 }}>
                <Input placeholder="选择档级后自动填充" disabled size="middle" style={{ height: 34 }} />
              </Form.Item>
              <Form.Item name="record" label="学历" rules={editFormRules.record} style={{ marginBottom: 12 }}>
                <Select placeholder="请选择学历" size="middle" style={{ height: 34 }}>
                  <Option value="">请选择</Option>
                  <Option value="高中">高中</Option>
                  <Option value="大专">大专</Option>
                  <Option value="本科">本科</Option>
                  <Option value="研究生">研究生</Option>
                  <Option value="博士">博士</Option>
                </Select>
              </Form.Item>

              {/* 第四行：开户行、银行卡号、政治面貌 */}
              <Form.Item name="bank" label="开户行" rules={editFormRules.bank} style={{ marginBottom: 12 }}>
                <Input placeholder="请输入开户行" size="middle" style={{ height: 34 }} />
              </Form.Item>
              <Form.Item name="bank_card" label="银行卡号" rules={editFormRules.bank_card} style={{ marginBottom: 12 }}>
                <Input
                  placeholder="请输入银行卡号"
                  onChange={(e) => {
                    const value = e.target.value.replace(/[^\d]/g, '');
                    editForm.setFieldValue('bank_card', value);
                  }}
                  size="middle"
                  style={{ height: 34 }}
                />
              </Form.Item>
              <Form.Item name="political_status" label="政治面貌" rules={editFormRules.political_status} style={{ marginBottom: 12 }}>
                <Select placeholder="请选择政治面貌" size="middle" style={{ height: 34 }}>
                  <Option value="">请选择</Option>
                  <Option value="群众">群众</Option>
                  <Option value="团员">团员</Option>
                  <Option value="党员">党员</Option>
                  <Option value="其他">其他</Option>
                </Select>
              </Form.Item>

              {/* 第五行：公司、项目、用工形式 */}
              <Form.Item name="companyid" label="公司" rules={editFormRules.companyid} style={{ marginBottom: 12 }}>
                <Select
                  placeholder="请选择公司"
                  onChange={handleEditCompanyChange}
                  size="middle"
                  style={{ height: 34 }}
                >
                  {companyOptions.map(company => <Option key={company.id} value={company.id}>{company.account}</Option>)}
                </Select>
              </Form.Item>
              <Form.Item name="projectid" label="项目" rules={editFormRules.projectid} style={{ marginBottom: 12 }}>
                <Select
                  placeholder={editForm.getFieldValue('companyid') ? "请选择项目" : "请先选择公司"}
                  onChange={handleEditProjectChange}
                  size="middle"
                  style={{ height: 34 }}
                >
                  {editCompanyProjects.map(project => (
                    <Option key={project.id} value={project.id}>{project.title}</Option>
                  ))}
                </Select>
              </Form.Item>
              <Form.Item name="layout" label="用工形式" rules={editFormRules.layout} style={{ marginBottom: 12 }}>
                <Select placeholder="请选择用工形式" size="middle" style={{ height: 34 }}>
                  <Option value="">请选择</Option>
                  <Option value={1}>长期派遣</Option>
                  <Option value={2}>短期派遣</Option>
                  <Option value={3}>学员</Option>
                </Select>
              </Form.Item>

              {/* 第六行：员工状态、合同到期时间、现合同期限 */}
              <Form.Item name="status" label="员工状态" rules={editFormRules.status} style={{ marginBottom: 12 }}>
                <Select
                  placeholder="请选择员工状态"
                  onChange={handleEditStatusChange}
                  size="middle"
                  style={{ height: 34 }}
                >
                  <Option value="">请选择</Option>
                  <Option value={1}>在岗</Option>
                  <Option value={2}>离职</Option>
                </Select>
              </Form.Item>
              <Form.Item name="agreement_end" label="合同到期时间" rules={editFormRules.agreement_end} style={{ marginBottom: 12 }}>
                <DatePicker style={{ width: '100%', height: 34 }} />
              </Form.Item>
              <Form.Item name="agreement_num" label="现合同期限" rules={editFormRules.agreement_num} style={{ marginBottom: 12 }}>
                <Input
                  placeholder="请输入合同期限"
                  onChange={(e) => {
                    const value = e.target.value.replace(/[^\d]/g, '');
                    editForm.setFieldValue('agreement_num', value);
                  }}
                  size="middle"
                  style={{ height: 34 }}
                />
              </Form.Item>

              {/* 第七行：单位社保基数、个人社保基数、入职时间 */}
              <Form.Item name="dw_security" label="单位社保基数" rules={editFormRules.dw_security} style={{ marginBottom: 12 }}>
                <Input placeholder="请输入单位社保基数" size="middle" style={{ height: 34 }} />
              </Form.Item>
              <Form.Item name="gr_security" label="个人社保基数" rules={editFormRules.gr_security} style={{ marginBottom: 12 }}>
                <Input placeholder="请输入个人社保基数" size="middle" style={{ height: 34 }} />
              </Form.Item>
              <Form.Item name="entry_time" label="入职时间" rules={editFormRules.entry_time} style={{ marginBottom: 12 }}>
                <DatePicker style={{ width: '100%', height: 34 }} />
              </Form.Item>

              {/* 第八行：离职时间 */}
              <Form.Item name="leave_time" label="离职时间" rules={editFormRules.leave_time} style={{ marginBottom: 0 }}>
                <DatePicker style={{ width: '100%', height: 34 }} />
              </Form.Item>
              <Form.Item /> {/* 占位，保持网格对齐 */}
              <Form.Item /> {/* 占位，保持网格对齐 */}
            </div>

            <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 16, gap: 8 }}>
              <Button onClick={handleEditCancel} size="middle" style={{ height: 34, padding: '0 16px' }}>取消</Button>
              <Button type="primary" htmlType="submit" loading={loading} size="middle" style={{ height: 34, padding: '0 16px' }}>确认更新</Button>
            </div>
          </Form>
        </Modal>
      </Card>
    </>
  );
};

export default EmployeeManagement;